package com.ruoyi.api;

import com.ruoyi.common.constant.ApiConstants;
import com.ruoyi.common.dto.AppController;
import com.ruoyi.common.utils.DataHandleUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.interceptor.annotation.IgnoreAuth;
import com.ruoyi.framework.interceptor.annotation.LoginUserId;
import com.ruoyi.framework.interceptor.annotation.RepeatSubmit;
import com.ruoyi.project.web.examReslut.domain.ExamReslut;
import com.ruoyi.project.web.examReslut.service.IExamReslutService;
import com.ruoyi.project.web.quesDetail.domain.QuesDetail;
import com.ruoyi.project.web.quesDetail.service.IQuesDetailService;
import com.ruoyi.project.web.videoClassify.domain.VideoClassify;
import com.ruoyi.project.web.videoClassify.service.IVideoClassifyService;
import com.ruoyi.project.web.videoInfo.domain.VideoInfo;
import com.ruoyi.project.web.videoInfo.service.IVideoInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author ywh
 * @date 2021/1/21
 * @desc 学习中心
 */

@RestController
@RequestMapping("/api/study")
public class StudyController extends AppController {

    @Autowired
    private IVideoClassifyService videoClassifyService;
    @Autowired
    private IVideoInfoService videoInfoService;
    @Autowired
    private IExamReslutService examReslutService;
    @Autowired
    private IQuesDetailService quesDetailService;


    /*视频分类*/
    @RequestMapping(value = "/selectVideoClassifyList")
    @IgnoreAuth
    public Object selectVideoClassifyList() {
        VideoClassify videoClassify = new VideoClassify();
        videoClassify.setStatus("0");
        List<VideoClassify> list = videoClassifyService.selectVideoClassifyList(videoClassify);
        return writeResultRep(list);
    }


    /**
     * 根据分类查询视频
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/selectVideoListByCid")
    @IgnoreAuth
    public Object selectVideoListByCid(Long classifyId, Integer pageNum, Integer pageSize) {
        if (StringUtils.isNull(pageNum) || StringUtils.isNull(pageSize) || StringUtils.isNull(classifyId)) {
            return toResponsFail("缺少参数");
        }
        VideoInfo videoInfo = new VideoInfo();
        videoInfo.setClassifyId(classifyId);
        videoInfo.setStatus("0");
        startPage();
        List<VideoInfo> list = videoInfoService.selectVideoInfoList(videoInfo);
        return writeResultRep(getDataTable(list));
    }


    /*需要考试列表*/
    @RequestMapping(value = "/queryNotExamList")
    public Object queryNotExamList(@LoginUserId Long userId, Integer pageNum, Integer pageSize) {
        if (StringUtils.isNull(pageNum) || StringUtils.isNull(pageSize)) {
            return toResponsFail("缺少参数传递");
        }
        /*答题并且过期===进行自动交卷*/
        List<ExamReslut> exList= examReslutService.selectEndList(userId);
        for (ExamReslut result : exList) {
            result.setStatus(ApiConstants.ok_join);
            result.setUpdateTime(DateUtils.getNowDate());
            examReslutService.updateExamReslut(result);
        }
        startPage();
        List<ExamReslut> list = examReslutService.queryNotExamList(userId);
        return writeResultRep(getDataTable(list));
    }

    /*开始考试--展示题目*/
    @RequestMapping(value = "/toExam")
    @RepeatSubmit
    public Object toExam(@LoginUserId Long userId, Long resultId) {
        if (StringUtils.isNull(resultId)) {
            return toResponsFail("缺少参数");
        }
        ExamReslut examReslut = examReslutService.selectExamReslutById(resultId);
        if (StringUtils.isNull(examReslut) || !userId.equals(examReslut.getUserId())) {
            return toResponsFail("信息有误");
        }
        if (examReslut.getStatus().equals(ApiConstants.ok_join)) {
            return toResponsFail("重复考试");
        }
        if (examReslut.getPaper().getEndTime().getTime() >= DateUtils.getNowDate().getTime()) {
            if (examReslut.getStartTime() == null) {
                examReslut.setStartTime(DateUtils.getNowDate());
                examReslut.setStatus(ApiConstants.answer_ing);
                examReslutService.updateExamReslut(examReslut);
            }
            ExamReslut data = examReslutService.selectEntityById(resultId);
            data.setNowDate(DateUtils.getNowDate());
            return writeResultRep(data);
        }
        return toResponsFail("考试时间已过期");
    }

    /*答题*/
    @RequestMapping(value = "/toAnswer")
    @Transactional
    public Object toAnswer(@LoginUserId Long userId, QuesDetail quesDetail, Double points, Long resultId, Boolean flag) {
        if (StringUtils.isNull(quesDetail) || StringUtils.isNull(flag) || StringUtils.isNull(resultId)) {
            return toResponsFail("检查传递参数");
        }
        ExamReslut examReslut = examReslutService.selectExamReslutById(resultId);
        if (StringUtils.isNull(examReslut) || !userId.equals(examReslut.getUserId())) {
            return toResponsFail("信息有误");
        }
        if (!quesDetail.getSortNum().equals(examReslut.getRunNum())){
            return toResponsFail("未按顺序答题");
        }
        try {
            /*1.记录答题号*/
            examReslut.setRunNum(quesDetail.getSortNum());
            /*2.记录正确错误量 和得分*/
            if (quesDetail.getRingtFlag().toUpperCase().equals("N")) {
                examReslut.setErrorNum(examReslut.getErrorNum() + 1);
            } else {
                examReslut.setScore(examReslut.getScore().add(new BigDecimal(points)));
                examReslut.setRightNum(examReslut.getRightNum() + 1);
            }
            /*3.判断是否最后一题--交卷*/
            if (flag) {
                /*是否合格（N-未通过，Y-合格）*/
                if (examReslut.getScore().doubleValue() > examReslut.getPaper().getPassPoints()) {  //
                    examReslut.setPassFlag("Y");
                }
                /*交卷时间*/
                examReslut.setUpdateTime(DateUtils.getNowDate());
                /*已交卷状态*/
                examReslut.setStatus(ApiConstants.ok_join);
            }
            /*4.计算正确率*/
            examReslut.setAccuracy(DataHandleUtil.division(examReslut.getRightNum(), examReslut.getPaper().getQuesNum()));
            /*5.总用时*/
            long between = (DateUtils.getNowDate().getTime() - examReslut.getStartTime().getTime()) / 1000;
            long min = between / 60;
            examReslut.setSpentStr(min + "分钟");
            int i = examReslutService.updateExamReslut(examReslut);
            /*6.保存做题记录*/
            if (i > 0) {
                quesDetail.setStatus("1");
                quesDetailService.updateQuesDetail(quesDetail);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toResponsFail("系统错误");
        }
        examReslut.setNowDate(DateUtils.getNowDate());
        return writeResultRep(examReslut);
    }

    /*自动交卷*/
    @RequestMapping(value = "/submitPaper")
    @RepeatSubmit
    @IgnoreAuth
    public Object submitPaper(Long resultId) {
        ExamReslut examReslut = new ExamReslut();
        examReslut.setResultId(resultId);
        examReslut.setStatus(ApiConstants.ok_join);
        examReslut.setUpdateTime(DateUtils.getNowDate());
        int i = examReslutService.updateExamReslut(examReslut);
        if (i > 0) {
            return writeResultRep(examReslut);
        }
        return toResponsFail("提交失败");
    }


    /*查看考试记录*/
    @RequestMapping(value = "/queryHadExamList")
    public Object queryHadExamList(@LoginUserId Long userId, Integer pageNum, Integer pageSize) {
        if (StringUtils.isNull(pageNum) || StringUtils.isNull(pageSize)) {
            return toResponsFail("缺少参数传递");
        }
        startPage();
        List<ExamReslut> list = examReslutService.queryHadExamList(userId);
        return writeResultRep(getDataTable(list));
    }

    /*查询以往考试结果*/
    @RequestMapping(value = "/queryHadExamById")
    @IgnoreAuth
    public Object queryHadExamById(Long resultId) {
        if (StringUtils.isNull(resultId)) {
            return toResponsFail("缺少参数");
        }
        ExamReslut examReslut = examReslutService.selectEntityById(resultId);
        return writeResultRep(examReslut);
    }

}
